package cn.tjad.tjad2.utils;

import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.hjy.http.download.FileDownloadInfo;
import com.hjy.http.download.FileDownloadTask;
import com.hjy.http.download.listener.OnDownloadProgressListener;
import com.hjy.http.download.listener.OnDownloadingListener;
import com.hjy.http.upload.FileUploadInfo;
import com.hjy.http.upload.FileUploadTask;
import com.hjy.http.upload.listener.OnUploadListener;
import com.hjy.http.upload.listener.OnUploadProgressListener;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;

import java.io.File;
import java.util.List;

import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.business.SettingManager;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.net.filedownload.FileDownloader;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

public class FileHandler implements IDataCallBack {

    public static final int ROOT_ID = 0;

    private Context context;
    private int type = 0; //0=项目文档  1=我的文档  2=回收站

    private String search = "";

    private int currentDisplayDirectoryId = ROOT_ID; //当前显示的路径ID

    private int currentDisplayDirectoryParentId = ROOT_ID; //当前显示的路径的上一级目录的id

    private OnFileListGetListener onFileListGetListener;
    private OnCreateFolderListener onCreateFolderListener;
    private OnFileUploadListener onFileUploadListener;
    private OnFileDeleteListener onFileDeleteListener;
    private OnFileRenameListener onFileRenameListener;
    private OnFileMoveListener onFileMoveListener;

    public FileHandler(Context context) {
        this.context = context;
    }

    public void requestFileList(int projectId, int id,  OnFileListGetListener listener) {
        this.onFileListGetListener = listener;
        RemoteDataService.getFileList(projectId, id, type, search, false, this);
    }

    public void requestFolder(int projectId, int id, OnFileListGetListener listener) {
        this.onFileListGetListener = listener;
        RemoteDataService.getFileList(projectId, id, type, search, true, this);
    }

    public void backToParent(int projectId, OnFileListGetListener listener) {
        search = "";
        if (currentDisplayDirectoryId != ROOT_ID) {
            requestFileList(projectId, currentDisplayDirectoryParentId, listener);
        }
    }

    public void setSearch(String search) {
        this.search = search;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getType() {
        return type;
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.FILE_LIST) {
            if (onFileListGetListener != null) {
                onFileListGetListener.onFileListFailed(errorMsg);
            }
        } else if (httpId == HttpId.CREATE_FOLDER) {
            if (onCreateFolderListener != null) {
                if (TextUtils.isEmpty(errorMsg)) {
                    errorMsg = "创建文件夹失败";
                }
                onCreateFolderListener.onCreateFolderFinished(false, errorMsg);
            }
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.FILE_LIST) {
            CommonBean<FileBean> bean = (CommonBean<FileBean>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                currentDisplayDirectoryId = bean.result.id;
                currentDisplayDirectoryParentId = bean.result.parentId;
                if (onFileListGetListener != null) {
                    onFileListGetListener.onFileListGet(bean.result.children);
                }
            } else {
                if (onFileListGetListener != null) {
                    onFileListGetListener.onFileListFailed(bean.respMsg);
                }
            }
        } else if (httpId == HttpId.CREATE_FOLDER) {
            CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                if (onCreateFolderListener != null) {
                    onCreateFolderListener.onCreateFolderFinished(true, "");
                }
            } else {
                if (onCreateFolderListener != null) {
                    onCreateFolderListener.onCreateFolderFinished(false, bean.respMsg);
                }
            }
        }
    }

    public  void createFolder(int projectId, String name, boolean mine, int parentId, OnCreateFolderListener listener) {
        this.onCreateFolderListener = listener;
        RemoteDataService.createFolder(projectId, mine, true, name, parentId, this);
    }

    public synchronized void uploadFile(int projectId, int parentId, String filePath, final OnFileUploadListener onFileUploadListener) {
        uploadFile(projectId, type == 1, parentId, filePath, onFileUploadListener);
    }

    public synchronized void uploadFile(int projectId, boolean mine, int parentId, String filePath, final OnFileUploadListener onFileUploadListener) {
        this.onFileUploadListener = onFileUploadListener;
        String id = String.valueOf(System.currentTimeMillis());
        RemoteDataService.uploadFile(projectId, id, mine, parentId, filePath, new OnUploadListener() {
            @Override
            public void onError(FileUploadTask uploadData, int errorType, String msg) {
                if (onFileUploadListener != null) {
                    onFileUploadListener.onFailed(uploadData.getFileUploadInfo(), errorType, msg);
                }
            }

            @Override
            public void onSuccess(FileUploadTask uploadData, Object data) {
                if (onFileUploadListener != null) {
                    onFileUploadListener.onSuccess(uploadData.getFileUploadInfo());
                }

            }
        }, new OnUploadProgressListener() {
            @Override
            public void onProgress(FileUploadTask uploadTask, long totalSize, long currSize, int progress) {
                if (onFileUploadListener != null) {
                    onFileUploadListener.onProgress(totalSize, currSize, progress);
                }
            }
        });
    }


    public void downloadFileWithCheck(Context context, final String url, final String fileName, final OnFileDownloadListener listener) {
        boolean pending = false;
        if (SettingManager.getTransferWithWifi()) {
            if (!NetworkUtils.isWifi(context)) {
                TjDialogFragment.Builder builder =  new TjDialogFragment.Builder(context);
                builder.setTitle("提示")
                        .setMessage("当前为非WIFI环境，继续下载可能会消耗较多流量，确认是否继续下载？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("继续", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialogInterface, int i) {
                                Tools.showToast("已添加至下载列表");
                                downloadFile(url, fileName, listener);
                                return true;
                            }
                        })
                        .show(((AppCompatActivity)context).getSupportFragmentManager());
            } else {
                Tools.showToast("已添加至下载列表");
                downloadFile(url, fileName, listener);
            }
        } else {
            Tools.showToast("已添加至下载列表");
            downloadFile(url, fileName, listener);
        }
    }

    public void downloadFile(String url, String fileName, final OnFileDownloadListener listener) {
        String id = String.valueOf(url);
        FileDownloader.getInstance().downloadFile(id, url, fileName, new OnDownloadingListener() {
            @Override
            public void onDownloadFailed(FileDownloadTask task, int errorType, String msg) {
                if (listener != null) {
                    listener.onFailed(task.getFileDownloadInfo(), errorType, msg);
                }
            }

            @Override
            public void onDownloadSucc(FileDownloadTask task, File outFile) {
                if (listener != null) {
                    listener.onSuccess(task.getFileDownloadInfo());
                }
            }
        }, new OnDownloadProgressListener() {
            @Override
            public void onProgressUpdate(FileDownloadTask downloadInfo, long current, long totalSize) {
                if (listener != null) {
                    int progress = (int) (current * 100.0 / totalSize);
                    listener.onProgress(downloadInfo.getFileDownloadInfo(), totalSize, current, progress);
                }
            }
        });
    }

    public void deleteFile(int projectId, List<Integer> ids, OnFileDeleteListener listener) {
        this.onFileDeleteListener = listener;
        RemoteDataService.deleteFile(projectId, ids, new IDataCallBack() {
            @Override
            public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
                if (onFileDeleteListener != null) {
                    onFileDeleteListener.onFileDelete(false, errorMsg);
                }
                return true;
            }

            @Override
            public void onDataRefresh(int httpId, Object responseBean) {
                CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
                if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                    if (onFileDeleteListener != null) {
                        onFileDeleteListener.onFileDelete(true, "");
                    }
                } else {
                    if (onFileDeleteListener != null) {
                        onFileDeleteListener.onFileDelete(false, bean.respMsg);
                    }
                }
            }
        });
    }

    public void renameFile(int projectId, int fileId, String newName, OnFileRenameListener listener) {
        this.onFileRenameListener = listener;
        RemoteDataService.renameFile(projectId, fileId, newName, new IDataCallBack() {
            @Override
            public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
                if (onFileRenameListener != null) {
                    onFileRenameListener.onFileRename(false, errorMsg);
                }
                return true;
            }

            @Override
            public void onDataRefresh(int httpId, Object responseBean) {
                CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
                if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                    if (onFileRenameListener != null) {
                        onFileRenameListener.onFileRename(true, "");
                    }
                } else {
                    if (onFileRenameListener != null) {
                        onFileRenameListener.onFileRename(false, bean.respMsg);
                    }
                }
            }
        });
    }

    public void moveFile(int projectId, int parentId, List<Integer> ids, OnFileMoveListener listener) {
        this.onFileMoveListener = listener;
        RemoteDataService.moveFile(projectId, parentId, ids, new IDataCallBack() {
            @Override
            public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
                if (onFileMoveListener != null) {
                    onFileMoveListener.onFileMove(false, errorMsg);
                }
                return true;
            }

            @Override
            public void onDataRefresh(int httpId, Object responseBean) {
                CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
                if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                    if (onFileMoveListener != null) {
                        onFileMoveListener.onFileMove(true, "");
                    }
                } else {
                    if (onFileMoveListener != null) {
                        onFileMoveListener.onFileMove(false, bean.respMsg);
                    }
                }
            }
        });
    }

    public void setOnFileListGetListener(OnFileListGetListener onFileListGetListener) {
        this.onFileListGetListener = onFileListGetListener;
    }

    public interface OnFileListGetListener {
        void onFileListGet(List<FileBean> fileList);
        void onFileListFailed(String message);
    }

    public interface OnFileUploadListener {
        void onProgress(long totalSize, long currSize, int progress);
        void onSuccess(FileUploadInfo fileUploadInfo);
        void onFailed(FileUploadInfo fileUploadInfo, int errorType, String errorMsg);
    }

    public interface OnFileDownloadListener {
        void onProgress(FileDownloadInfo fileUploadInfo, long totalSize, long currSize, int progress);
        void onSuccess(FileDownloadInfo fileUploadInfo);
        void onFailed(FileDownloadInfo fileUploadInfo, int errorType, String errorMsg);
    }

    public interface OnCreateFolderListener {
        void onCreateFolderFinished(boolean success, String message);
    }

    public interface OnFileDeleteListener {
        void onFileDelete(boolean success, String message);
    }

    public interface OnFileRenameListener {
        void onFileRename(boolean success, String message);
    }

    public interface OnFileMoveListener {
        void onFileMove(boolean success, String message);
    }

    public boolean isShowRoot() {
        return currentDisplayDirectoryId == ROOT_ID;
    }

    public int getCurrentDisplayDirectoryId() {
        return currentDisplayDirectoryId;
    }
}
